import axios from 'axios'

// create an axios instance  创建一个axios实例
const service = axios.create({
  withCredentials: true, // send cookies when cross-domain requests (跨域请求，允许保存cookie)
  timeout: 30000 // request timeout (超时时间)
})
service.defaults.headers.post['Content-Type'] = "application/json;charset=utf-8"
// request interceptor 请求后台接口拦截
/**
 * 根据本项目要求，每个请求头部都要有access_token、name字段
 */
service.interceptors.request.use(
  config => { 
    // do something before request is sent
    let token = localStorage.getItem('Authorization');
    if (token) { // 登录状态 TODO 需要修改具体情况
      // let each request carry token
      // console.log(token,'token');
      config.headers['access_token'] = token
      // config.headers['Cookie'] = token
    } else { // 无登录用户状态
      config.headers['access_token'] = ''
      config.headers['name'] = ''
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor 返回请求拦截
service.interceptors.response.use(
  response => {
    const res = response.data

    // if the custom code is not 200, it is judged as an error.
    if (res.code && res.code !== 200) {
   
       if( res.code == 401){
        localStorage.removeItem('Authorization');
        this.$router.push('/login');
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Notify({
      message: error.message,
      type: 'danger',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service